from django.conf import settings
from django.db.models import get_model
from opinion_extractor.respondent.exceptions import RespondentProfileImproperlyConfigured


def get_respondent_model():
    """
    Return the model class for the currently-active respondent profile
    model, as defined by the ``OPINION_EXTRACTOR['respondent_profile_model']``
    setting. If that setting is missing, raise
    ``opinion_extractor.respondent.exceptions.RespondentProfileImproperlyConfigured``.
    """
    if hasattr(settings, 'OPINION_EXTRACTOR') and \
      'respondent_profile_model' in settings.OPINION_EXTRACTOR and\
      settings.OPINION_EXTRACTOR['respondent_profile_model']:
        respondent_model = get_model(
            *settings.OPINION_EXTRACTOR['respondent_profile_model'].split('.')
        )
        if respondent_model is None:
            raise RespondentProfileImproperlyConfigured
        return respondent_model
    else:
        raise RespondentProfileImproperlyConfigured


def get_respondent_default_manager():
    return get_respondent_model()._default_manager


def get_latest_respondent_profile(user, additional_filter=None):
    from datetime import date
    filt = get_respondent_default_manager().valid_on_date(date.today())
    if additional_filter:
        filt = filt.filter(additional_filter)
    return filt.get(user=user)
